package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityAppInfo;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.ActivityCollectUtil;
import com.yuwj.chinaa.util.GlideImageLoader;
import com.yuwj.chinaa.util.InstallApkUtil;
import com.yuwj.chinaa.util.SharedpreferenceUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 账户设置界面
 */
public class AccountSettingActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_user_photo)
    CircleImageView civUserPhoto;
    @BindView(R.id.tv_version_code)
    TextView tvVersionCode;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    IPresenter presenter;
    AlertDialog alertDialogWithUpdate;

    public static Intent createIntent(Context context) {
        return new Intent(context, AccountSettingActivity.class);
    }


    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_account_setting;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
    }

    @Override
    public void initView() {
        tvTitle.setText("个人设置");
//        // 获取当前软件版本
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo != null) {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            int localVersionCode = packageInfo.versionCode;
            String localVersionName = packageInfo.versionName;
            tvVersionCode.setText(localVersionName + "");
        }
        entityUser = SharedpreferenceUtil.getInstance().getUserInfo(context);
        String imgUrl = entityUser.getPic();
        Glide.with(context).load(imgUrl).error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
        tvNickname.setText(entityUser.getName() + "");

    }

    @Override
    public void initOperator() {


    }

    @OnClick({R.id.iv_back, R.id.ll_setting_toux, R.id.ll_setting_nickname, R.id.ll_setting_update_pwd, R.id.ll_setting_update_pay_pwd, R.id.ll_setting_update_phone,
            R.id.ll_setting_safe_auth, R.id.ll_setting_realname_auth, R.id.ll_version_container})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.ll_setting_toux:
                dialogShowPhotoSelect(this);
                break;
            case R.id.ll_setting_nickname:
                startActivity(AccountUpdateNicknameActivity.createIntent(context));
                break;
            case R.id.ll_setting_update_pwd:
                startActivity(AccountUpdateLoginPasswordActivity.createIntent(context));
                break;
            case R.id.ll_setting_update_pay_pwd:
                startActivity(AccountUpdatePaymentPasswordActivity.createIntent(context));
                break;
            case R.id.ll_setting_update_phone:
                startActivity(AccountUpdatePhoneActivity.createIntent(context));
                break;
            case R.id.ll_setting_safe_auth:
                startActivity(AccountSafetyCertificateActivity.createIntent(context));
                break;
            case R.id.ll_setting_realname_auth:
                switch (entityUser.getIsIdentification()) {
                    case ConstantParam.GENERAL_AUTH_WITH_NO:
                        startActivity(AccountAuthenticationInputActivity.createIntent(context));
                        break;
                    case ConstantParam.GENERAL_AUTH_WITH_ING:
                        startActivity(AccountAuthenticationInreviewActivity.createIntent(context));
                        break;
                    case ConstantParam.GENERAL_AUTH_WITH_SUCCESS:
                        startActivity(AccountAuthenticationSuccessActivity.createIntent(context));
                        break;
                    case ConstantParam.GENERAL_AUTH_WITH_FAIL:
                        startActivity(AccountAuthenticationFailActivity.createIntent(context));
                        break;
                    default:
                        startActivity(AccountAuthenticationInputActivity.createIntent(context));
                        break;
                }
                break;
//            case R.id.ll_contact_us:
//                startActivity(AccountContactUsActivity.createIntent(context));
//                break;
            case R.id.ll_version_container:
                JSONObject paramWithAppInfo = new JSONObject();
                try {
                    paramWithAppInfo.put("isIos", "2");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.appInfo(paramWithAppInfo.toString());
                break;
        }
    }

    NiceDialog niceDialogShowSelectPhoto;
    ImagePicker imagePicker;
    public int REQ_CODE_SELECT_IMAGE = 1;//拍照和选择图片的请求码

    /**
     * 弹框显示图片选择界面
     *
     * @param fragmentActivity
     */
    public void dialogShowPhotoSelect(final FragmentActivity fragmentActivity) {
        if (niceDialogShowSelectPhoto == null) {
            niceDialogShowSelectPhoto = NiceDialog.init();
            niceDialogShowSelectPhoto.setLayoutId(R.layout.content_userinfo_select_photo);
        }
        niceDialogShowSelectPhoto.setConvertListener(new ViewConvertListener() {
            @Override
            protected void convertView(ViewHolder viewHolder, final BaseNiceDialog baseNiceDialog) {

                TextView tvSelectPhoto = viewHolder.getView(R.id.tv_select_photo);
                TextView tvTakePhoto = viewHolder.getView(R.id.tv_take_photo);
                TextView tvCancel = viewHolder.getView(R.id.tv_cancel);
                View.OnClickListener onClickListener = new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_select_photo:
                                if (imagePicker == null) {
                                    imagePicker = ImagePicker.getInstance();
                                    imagePicker.setImageLoader(new GlideImageLoader());
                                    imagePicker.setMultiMode(false);
                                    imagePicker.setStyle(CropImageView.Style.CIRCLE);
                                    imagePicker.setShowCamera(false);
                                    imagePicker.setCrop(true);
                                    imagePicker.setSaveRectangle(false);
                                    imagePicker.setSelectLimit(1);

                                    DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
                                    int screenWidth = curMetrics.widthPixels;
                                    int screenHeight = curMetrics.heightPixels;
                                    imagePicker.setFocusWidth(screenWidth / 2);
                                    imagePicker.setFocusHeight(screenHeight / 2);


                                }
                                Intent intent = new Intent(context, ImageGridActivity.class);
                                startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
                                break;
                            case R.id.tv_take_photo:
                                if (imagePicker == null) {
                                    imagePicker = ImagePicker.getInstance();
                                    imagePicker.setImageLoader(new GlideImageLoader());
                                    imagePicker.setMultiMode(false);
                                    imagePicker.setStyle(CropImageView.Style.CIRCLE);
                                    imagePicker.setShowCamera(true);
                                    imagePicker.setCrop(true);
                                    imagePicker.setSaveRectangle(false);
                                    imagePicker.setSelectLimit(1);
                                    DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
                                    int screenWidth = curMetrics.widthPixels;
                                    int screenHeight = curMetrics.heightPixels;
                                    imagePicker.setFocusWidth(screenWidth / 2);
                                    imagePicker.setFocusHeight(screenHeight / 2);

                                }
                                Intent intent2 = new Intent(context, ImageGridActivity.class);
                                intent2.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);//直接打开照相机
                                startActivityForResult(intent2, REQ_CODE_SELECT_IMAGE);
                                break;
                        }
                        baseNiceDialog.dismiss();
                    }
                };

                tvTakePhoto.setOnClickListener(onClickListener);
                tvSelectPhoto.setOnClickListener(onClickListener);
                tvCancel.setOnClickListener(onClickListener);
            }
        })
                .setDimAmount(0.3f)
                .setOutCancel(true)
                .setShowBottom(true);
        niceDialogShowSelectPhoto.show(fragmentActivity.getSupportFragmentManager());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQ_CODE_SELECT_IMAGE) {
                File file = new File(ConstantParam.UPLOAD_COMPRESS_MEDIA_PATH);
                if (!file.exists()) {
                    file.mkdirs();
                }
                final ArrayList<ImageItem> imageItemList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItemList != null && imageItemList.size() > 0) {
                    ImageItem selectedImageItem = imageItemList.get(0);
                    String imgPath = selectedImageItem.path;
                    Luban.with(this)
                            .load(imgPath)                                   // 传入要压缩的图片列表
                            .ignoreBy(100)                                  // 忽略不压缩图片的大小
                            .setTargetDir(ConstantParam.UPLOAD_COMPRESS_MEDIA_PATH)                        // 设置压缩后文件存储位置
                            .setCompressListener(new OnCompressListener() { //设置回调
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(File file) {
                                    String filePath = file.getAbsolutePath();
                                    JSONObject param = new JSONObject();
                                    try {
                                        param.put("uploadtype", 2 + "");//1.交易证明，2.头像上传

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    presenter.appUploadFilesImage(param.toString(), filePath);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    ToastUtil.getInstance().shortLength(context, "压缩图片失败");
                                }
                            }).launch();    //启动压缩
                }
            } else {
                ToastUtil.getInstance().shortLength(context, "没有数据");
            }
        }
    }


    @Override
    public void appUploadFilesImageSuccess(String imgUrl) {
        super.appUploadFilesImageSuccess(imgUrl);
        boolean isHasSetUserPhotoInterface = false;
        if (isHasSetUserPhotoInterface) {
            JSONObject param = new JSONObject();
            try {
                param.put("userId", entityUser.getUserId());
                param.put("headUrl", imgUrl);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            presenter.userUploadImg(param.toString());
        } else {
            entityUser.setPic(imgUrl);
            SharedpreferenceUtil.getInstance().saveUserInfo(context, entityUser);
            Glide.with(context).load(entityUser.getPic()).error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
        }

    }

    @Override
    public void appUploadFilesImageFail(Exception e) {
        super.appUploadFilesImageFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");
    }

    @Override
    public void onUserUploadImgSuccess(String photoUrl) {
        super.onUserUploadImgSuccess(photoUrl);
        entityUser.setPic(photoUrl);
        SharedpreferenceUtil.getInstance().saveUserInfo(context, entityUser);
        Glide.with(context).load(entityUser.getPic()).error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
    }

    @Override
    public void onUserUploadImgFail(Exception e) {
        super.onUserUploadImgFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }

    @Override
    public void onAppInfoSuccess(final EntityAppInfo entityAppInfo) {
        super.onAppInfoSuccess(entityAppInfo);
        // 获取当前软件版本
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return;
        }
        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        int localVersionCode = packageInfo.versionCode;
        String localVersionName = packageInfo.versionName;
        // 服务端软件版本
        String serverVersionCode = entityAppInfo.getVersion();
        if (!serverVersionCode.equals(localVersionName)) {
            //弹出对话框提示版本更新.
//            new CheckUpdateUtil().showUpdateTipDialog(AccountSettingActivity.this, entityAppInfo, 1);
            if (alertDialogWithUpdate == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            Uri uri = Uri.parse(entityAppInfo.getDownloadurl().trim());
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 退出程序
                        ActivityCollectUtil.getInstance().finishAll();
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                    }
                }).setTitle("版本更新").setMessage(entityAppInfo.getContent() + "");

                alertDialogWithUpdate = builder.create();
                alertDialogWithUpdate.setCanceledOnTouchOutside(false);
                alertDialogWithUpdate.setCancelable(false);
            }
            alertDialogWithUpdate.show();
        } else {
            ToastUtil.getInstance().shortLength(context, "已是最新版本");
        }
    }

    @Override
    public void onAppInfoFail(Exception e) {
        super.onAppInfoFail(e);
    }

    public IPresenter getPresenter() {
        return presenter;
    }

    public void setPresenter(IPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onDownloadFileSuccess(File file) {
        super.onDownloadFileSuccess(file);
        String fileName = file.getName();
        if (fileName.endsWith("apk")) {
            //安装
            new InstallApkUtil().installApk(context, file.getAbsolutePath());
        }
    }
}
